package com.youease.chris.manager
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	public class ImageLoader
	{
		private var loadQueue:Vector.<Object> = new Vector.<Object>();
		private var loading:Boolean = false;
		private var loader:Loader = new Loader();
		
		private var sources:Dictionary = new Dictionary();
		
		private var loadObj:Object = new Object();
		
		private static var _instance:ImageLoader;
		
		public function ImageLoader()
		{
			super();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onCompleteHandler);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
		}
		
		public static function get instance():ImageLoader {
			if(!_instance) {
				_instance = new ImageLoader();
			}
			return _instance;
		}
		
		public function get isloading():Boolean {
			return this.loading;
		}

		public function loadImg(img:String,id:Object,prop:String):void {
			if(sources[img]&&sources[img]!=1) {
				id[prop] = sources[img];
				return;
			}
			var obj:Object = new Object();
			obj.img = img;
			obj.id = id;
			obj.prop = prop;
			loadQueue.push(obj);
			if(!loading) {
				load();
				loading = true;
			}
		}
		
		
		private function load():void {
			if(loadQueue.length>0) {
				loadObj = loadQueue.pop();
				if(sources[loadObj.img]) {
					loadObj.id[loadObj.prop] = sources[loadObj.img];
					load();
				}else {
					sources[loadObj.img] = 1;//标记这张图片正在加载中
					var urlRequest:URLRequest = new URLRequest(loadObj.img);
					loader.load(urlRequest);
				}
			}else {
				loading = false;
			}
		}
		
		private function onCompleteHandler(evt:Event):void {
			loadObj.id[loadObj.prop] = loader.content["bitmapData"];
			sources[loadObj.img] = loadObj.id[loadObj.prop];
			load();
		}
		
		public function clear():void {
			loadObj = new Object();
			sources = new Dictionary();
			loadQueue = new Vector.<Object>();
		}
		
		private function onError(evt:Event):void {
			trace(evt.toString()+"图片加载失败");
		}
	}
}
